package kr.co.happenstance;

import kr.co.happenstance.lib.MemberLib;
import kr.co.happenstance.lib.vo.LibResultVo;
import kr.co.happenstance.lib.vo.MemberCheckResultVo;
import kr.co.happenstance.util.AndroidUtil;

import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.google.android.gcm.GCMRegistrar;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class IntroActivity extends BaseActivity{
	protected final String TAG="<<<IntroActivity>>>";
	
	/**
	 * 애니메이션 대상 ImageView 객체
	 */
	private ImageView ivIntroAni;
	
	/**
	 * 애니메이션 구동을 위한 AnimationDrawable 객체
	 */
	private AnimationDrawable frameAnimation;
		
	private boolean notiFlag;
	private int matchingRequestSeq;
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro);
		
		notiFlag = getIntent().getBooleanExtra("notiFlag", false);
		matchingRequestSeq = getIntent().getIntExtra("matchingRequestSeq", -1);
		Log.d(TAG, "notiFlag["+notiFlag+"]");
		Log.d(TAG, "matchingRequestSeq["+matchingRequestSeq+"]");
		
		ivIntroAni = (ImageView) this.findViewById(R.id.iv_intro_ani);
		ivIntroAni.setBackgroundResource(R.anim.intro_animation);
		frameAnimation = (AnimationDrawable) ivIntroAni.getBackground();
		frameAnimation.start();
		
		
		//allowLoginUI을 false 로 해서 상태 체크만 하고 페이스북 로그인창은 보이지 않게함
		//StatusCallback도 사용하지 않기 때문에 그냥 null값으로 넘김
		Session.openActiveSession(this, false, null);		
		
		if(AndroidUtil.isNetworkConnectionAvailable(this)){
			//네트웍 가능시 페이스북 로그인 체크및 GCM registerId 체크 
			new FacebookLoginChkTask().execute();
			
			//GCM 체크및 등록 요청 
			GCMRegistrar.checkDevice(this);
			GCMRegistrar.checkManifest(this);
			
			final String regId = GCMRegistrar.getRegistrationId(this);
			//GCMRegistrar.unregister(this);
			if(regId == null || regId.equals("")){
				GCMRegistrar.register(this, GCMIntentService.PROJECT_ID);
			}else{
				Log.d(TAG, "regId["+regId+"]");
				AndroidUtil.setAppPreferences(this, C.SHARED_PREF_NAME, C.SHARED_PREF_KEY_GCMID, regId);
			}
			addActivity(this);
			
		}else{
			//네트웍 불가능시 안내후 어플 종료
			new CustomAlertDialogBuilder(IntroActivity.this)
			.setTitle(IntroActivity.this.getString(R.string.alert_title))
			.setMessage(getString(R.string.alert_msg_network_disable))
			.setCancelable(false)
			.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int arg1) {
					dialog.dismiss();
					IntroActivity.this.finish();
					
				}
			})
			.create();				
		}
		
		
	}
	
	
	/**
	 * 페이스북 로그인 체크 Task 클래스<br><br>
	 * 
	 * intro 애니메이션을 보여 주기위해 별도 쓰레든에서 페이스북 로그인 체크를 하기 위해 Task 클래스로 구현
	 * 
	 * @author Administrator
	 *
	 */
	private class FacebookLoginChkTask extends AsyncTask<Void, Void, Void>{
		@Override
		protected Void doInBackground(Void... params) {
			try{
				//무조건 애니메이션 효과를 한번 보여 주기 위해 sleep 줌
				Thread.sleep(2000);
			}catch(Exception e){}
			
			//intro 애니메이션 멈춤
			frameAnimation.stop();
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			//Facebook 로그인 체크
			
			Session session = Session.getActiveSession(); 
			if(session == null || !session.isOpened()){
				//페이스북 로그아웃 상태일때 로그인Activity로 이동 
				Intent intent = new Intent(IntroActivity.this, LoginActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				IntroActivity.this.finish();
				
			}else{
				//페이스북 로그인 상태일때 정보 요청(비동기식임)
				Request meRequest = Request.newMeRequest(session, new Request.GraphUserCallback(){
					@Override
					public void onCompleted(GraphUser user, Response response) {
						FacebookRequestError error = response.getError();
						if(error != null){
							Log.e(TAG, error.toString());
							
							//페이스북 정보 조회 오류시 Alert후 App 종료
							new CustomAlertDialogBuilder(IntroActivity.this)
							.setTitle(IntroActivity.this.getString(R.string.alert_title))
							.setMessage(getString(R.string.alert_msg_facebook_get_info_error))
							.setCancelable(false)
							.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener(){
								@Override
								public void onClick(DialogInterface dialog, int arg1) {
									dialog.dismiss();
									IntroActivity.this.finish();
								}
							})
							.create();								
							
						}else{
							String info = user.getInnerJSONObject().toString();
							Log.d(TAG, info);
							
							try{
								
								myApp.id = user.getId();
								Log.d(TAG, "id["+myApp.id+"]");
								
								myApp.birthday = user.getBirthday();
								Log.d(TAG, "birthday["+myApp.birthday+"]");
								
								myApp.gender = user.getInnerJSONObject().getString("gender");
								Log.d(TAG, "gender["+myApp.gender+"]");
								
								myApp.email = user.getInnerJSONObject().getString("email");
								Log.d(TAG, "email["+myApp.email+"]");
								
								
							}catch(Exception e){
								e.printStackTrace();
								
							}finally{
								if(	myApp.id != null && !myApp.id.equals("") && 
									myApp.birthday != null && !myApp.birthday.equals("") &&
									myApp.gender != null && !myApp.gender.equals("") 
								){
									//필수 정보 취득 성공시
									
									//이메일 정보 체크
									if(myApp.email == null) myApp.email = "";
									
									Log.d(TAG, "email["+myApp.email+"]");
									
									//프로필 사진 url 셋팅
									myApp.profileLargeUrl = C.FACEBOOK_PROIFILE_URL+myApp.id+"/picture?type=large";
									myApp.profileNormalUrl = C.FACEBOOK_PROIFILE_URL+myApp.id+"/picture?type=normal";
									myApp.profileSmallUrl = C.FACEBOOK_PROIFILE_URL+myApp.id+"/picture?type=small";
									myApp.profileSquareUrl = C.FACEBOOK_PROIFILE_URL+myApp.id+"/picture?type=square";
									
									Log.d(TAG, "profileLargeUrl["+myApp.profileLargeUrl+"]");
									Log.d(TAG, "profileNormalUrl["+myApp.profileNormalUrl+"]");
									Log.d(TAG, "profileSmallUrl["+myApp.profileSmallUrl+"]");
									Log.d(TAG, "profileSquareUrl["+myApp.profileSquareUrl+"]");
									
									new IntroTask().execute();
									
								}else{
									//필수 정보 취득 실패시 Alert후 App종료
									new CustomAlertDialogBuilder(IntroActivity.this)
									.setTitle(IntroActivity.this.getString(R.string.alert_title))
									.setMessage(getString(R.string.alert_msg_facebook_get_info_error))
									.setCancelable(false)
									.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener(){
										@Override
										public void onClick(DialogInterface dialog, int arg1) {
											dialog.dismiss();
											IntroActivity.this.finish();
										}
									})
									.create();										
								}
								
							}
							
							
							
							
							
						}
					}
					
				});
				
				Bundle params = new Bundle();
				params.putString("fields","name, picture, locale, gender, email, birthday");
				meRequest.setParameters(params);
				meRequest.executeAsync();
				showProgress();
			}			
		}
	}
	
	private class IntroTask extends AsyncTask<Void, Void, Integer> {
		/**
		 * Exception 발생시 (어플종료)
		 */
		private final int RESULT_EXCEPTION = 0;
		
		/**
		 * 로그인 최종 성공 (메인 페이지로 이동)
		 */
		private final int RESULT_SUCCESS = 1;
		
		/**
		 * 회원 조회 결과 - 회원이 아님 (회원가입창 호출)
		 */
		private final int RESULT_MBR_NOT = 2;
		
		/**
		 * 회원조회결과 - 탈퇴,차단 회원(어플종료)
		 */
		private final int RESULT_MBR_ERROR = 3;
		
		/**
		 * 위치정보 조회 실패시(어플종료)
		 */
		private final int RESULT_GPS_ERROR = 4;
		
		/**
		 * GCM ID 존재하지 않을때 (어플종료)
		 */
		private final int RESULT_GCM_ERROR = 5;

		
		/**
		 * 결과 메세
		 */
		private String message = "";
		
		@Override
		protected Integer doInBackground(Void... params) {
			int result = RESULT_SUCCESS;
			try{
				MemberLib lib = new MemberLib();
				
				//회원가입 여부 체크
				MemberCheckResultVo resultVo = (MemberCheckResultVo) lib.memberCheck(myApp.id);
				if(resultVo == null){
					throw new Exception("MemberCheckResultVo Null....");
				}
				
				//결과 메세지
				message = resultVo.getMessage();
				
				if(resultVo.getMemberGbn().equals(C.MEMBER_GBN_NOT)){
					//비회원
					result = RESULT_MBR_NOT;
					
				}else if(resultVo.getMemberGbn().equals(C.MEMBER_GBN_BREAK) || resultVo.getMemberGbn().equals(C.MEMBER_GBN_REMOVE)){
					//차단,탈퇴 회원
					result = RESULT_MBR_ERROR;
					
				}else{
					//정상회원 ==> 로그인
					//Log.d(TAG, "Latitude["+myLocation.getLatitude()+"]");
					//Log.d(TAG, "Longitude["+myLocation.getLongitude()+"]");						
					
					if(myLocation == null){
						result = RESULT_GPS_ERROR;
						message = IntroActivity.this.getResources().getString(R.string.alert_msg_gps_error);
						
					}else{
						//GCM ID 체크 
						String gcmId = AndroidUtil.getAppPreferences(IntroActivity.this, C.SHARED_PREF_NAME, C.SHARED_PREF_KEY_GCMID);
						if(gcmId == null || gcmId.equals("")){
							result = RESULT_GCM_ERROR;
							message = IntroActivity.this.getResources().getString(R.string.alert_msg_gcm_error);
							
						}else{
							
							//로그인 시도 
							LibResultVo loginResultVo = (LibResultVo) lib.login(myApp.id, myApp.gender, myApp.birthday, myApp.email, Double.toString(myLocation.getLatitude()), Double.toString(myLocation.getLongitude()), gcmId);
							if(loginResultVo == null || loginResultVo.getResult().equals(C.API_RESULT_VALUE_FAIL)){
								throw new Exception("LoginResultVo.....Null Or Fail");
							}
							
						}
						
					}
				}

			}catch(Exception e){
				e.printStackTrace();
				message = IntroActivity.this.getResources().getString(R.string.alert_msg_exception);
				result = RESULT_EXCEPTION;
			}
			return result;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			closeProgress();
			Intent intent  =  null;
			switch(result){
				case RESULT_EXCEPTION:
				case RESULT_MBR_ERROR:
				case RESULT_GPS_ERROR:
				case RESULT_GCM_ERROR:	
					new CustomAlertDialogBuilder(IntroActivity.this)
					.setTitle(IntroActivity.this.getString(R.string.alert_title))
					.setMessage(message)
					.setCancelable(true)
					.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener(){
						@Override
						public void onClick(DialogInterface dialog, int arg1) {
							dialog.dismiss();
							IntroActivity.this.finish();
						}
					})
					.create();						
					break;
					
				case RESULT_MBR_NOT:
					intent = new Intent(IntroActivity.this, ClauseActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					break;
					
				case RESULT_SUCCESS:
					Log.d(TAG, "Login Success.........");
					if(notiFlag){
						intent = new Intent(IntroActivity.this, PushMeetActivity.class);
						intent.putExtra("matchingRequestSeq", matchingRequestSeq);
					}else{
						intent = new Intent(IntroActivity.this, HomeActivity.class);
					}
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);					
					IntroActivity.this.finish();
					break;
					
			}
			
		}
			
		
	}


	
}
